package cn.wolfcode.elasticjob.job;

import cn.wolfcode.elasticjob.domain.FileCustom;
import cn.wolfcode.mapper.FileCustomMapper;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 任务类：数据库中有一些列的数据，需要对这些数据进行备份操作，备份完之后，修改数据的状态，标记已经备份了。
 */
@Component
public class FileCustomJob implements SimpleJob {
    @Autowired
    private FileCustomMapper fileCustomMapper;

    @Override
    public void execute(ShardingContext shardingContext) {
        System.out.println("ShardingParameter:" + shardingContext.getShardingParameter());
        System.out.println("ShardingItem:" + shardingContext.getShardingItem());
        doWork(shardingContext.getShardingParameter());
    }

    private void doWork(String shardingParameter) {
        List<FileCustom> fileList = fileCustomMapper.selecByType(shardingParameter);
        System.out.println("线程id  ：" + Thread.currentThread().getId());
        System.out.println("分片的类型为：" + shardingParameter + "此次需要备份文件个数:" + fileList.size());
        for (FileCustom fileCustom : fileList) {
            backUpFile(fileCustom);
        }
    }

    private void backUpFile(FileCustom fileCustom) {
        try {
            //模拟备份动作,假设一堆操作花一秒钟
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("执行文件备份====> id:" + fileCustom.getId() + "   类型：" + fileCustom.getType());
        fileCustomMapper.changeState(fileCustom.getId(), 1);
    }
}
